package com.xiaoq.sites.repository.impl;

import static org.mongodb.morphia.aggregation.Group.first;
import static org.mongodb.morphia.aggregation.Group.grouping;
import static org.mongodb.morphia.aggregation.Group.id;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.xiaoq.coms.util.ConstantUtil;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.aggregation.Accumulator;
import org.mongodb.morphia.aggregation.AggregationPipeline;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.Sort;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.sites.entity.SitesHotSearchEntity;
import com.xiaoq.sites.repository.ISitesHotSearchRepository;

@Repository
public class SitesHotSearchRepositoryImpl implements ISitesHotSearchRepository{
	
	@Autowired
	private Datastore datastore;
	
	public void addSitesHotSearch(SitesHotSearchEntity sitesHotSearch) {
		datastore.save(sitesHotSearch);
	}

	@Override
	public List<SitesHotSearchEntity> getSitesHotSearchList() {
		List<SitesHotSearchEntity> resultList = new ArrayList<>();
		Query<SitesHotSearchEntity> query = datastore.createQuery(SitesHotSearchEntity.class);
		AggregationPipeline pipeline = datastore.createAggregation(SitesHotSearchEntity.class)
				.match(query.filter("type =", 0).filter("searchType", ConstantUtil.SEARCH_RESULT_TYPE_SITES))
				.group(id(grouping("shopId")),   //以 matchTxt 分组
						grouping("matchTxt",first("matchTxt")),
						grouping("zoneCity",first("zoneCity")),
						grouping("shopId",first("shopId")),
						grouping("searchType",first("searchType")),
						grouping("type",first("type")),
                        grouping("count",new Accumulator("$sum", 1))
                        ).sort(Sort.descending("count"))
				.limit(10);
		Iterator<SitesHotSearchEntity> iterator = pipeline.aggregate(SitesHotSearchEntity.class);
		
        while (iterator.hasNext()) {
			SitesHotSearchEntity searchEntity = iterator.next();
			resultList.add(searchEntity);
        }
		return resultList;
	}
	
}
